<template>
  <div class="table-demo-wrapper">
    <div class="component-example">
      <label class="example-title">使用示例</label>
      <div class="example">
        <table-view :cols="cols" :tableData="tableData" :canCheck="true" :showSearch="searchCondition.length > 0"
                    :searchCondition="searchCondition" :showOperate="true" :buttonCount="1"
                    :operateSameButton="true" :showPaginator="true" :clearSelect="clearSelect"
                    :pageNumber="pageNumber" :pageSize="pageSize" :totalRecords="totalRecords"
                    :operateButtons="operateButtons" :showSearchButton="true" @on-search="searchData"
                    @size-change="sizeChange" @current-page-change="pageChange" @preClick="pageChange"
                    @nextClick="pageChange" @selection-change="selectChange" @on-operate="clickOperate">
          <div class="operate-button-group">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="operate('add')">新增</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="operate('del')">批量删除</el-button>
          </div>
        </table-view>
        <el-dialog :title="dialogTitle" width="500px" :visible.sync="dialogVisible">
          <div class="dialog-content">
            <p class="dialog-container" v-if="showDel">{{ showDelContent }}</p>

            <form-view class="form-view" v-else :items="attr" :add-form="value"
                       :labelWidth="'35%'" :valueWidth="'80%'" ref="formRef"/>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button class="confirm-btn" type="primary" size="small" @click="submit">确 认</el-button>
            <el-button class="cancel-btn" size="small" @click="dialogVisible = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="component-document">
      <div class="import-property">
        <label class="prop-title">输入属性</label>
        <ul class="prop-lists">
          <li class="prop-item" v-for="(item,index) in tableProps" :key="index">
            <label class="prop-name">{{ item.name }}：</label>
            <span class="prop-desc">{{ item.desc }}</span>
          </li>
        </ul>
      </div>
      <div class="output-method">
        <label class="prop-title">输出方法</label>
        <ul class="prop-lists">
          <li class="prop-item" v-for="(item,index) in tableMethods" :key="index">
            <label class="prop-name">{{ item.name }}：</label>
            <span class="prop-desc">{{ item.desc }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
 import TableView from "../../components/el-extend-components/TableView/TableView.vue";
export default {
  name: 'TableDemo',
  components: {
    TableView
  },
  data() {
    return {
      urls: {
        getTableHeaderUrl: './static/json/user-manage-header.json',
        getTableDataUrl: './static/json/user-manage-data.json',
        // getTableHeaderUrl: remoteUrl + '/demo/test/table/account_details/header', // 获取表头数据
        // getTableDataUrl: remoteUrl + '/demo/test/table/account_details', // 获取表格数据
        saveDataUrl: remoteUrl + '/demo/test/table/edit/account_details', // 新增、编辑
        deleteDataUrl: remoteUrl + '/demo/test/table/account_details', // 删除
        deleteInBatches: remoteUrl + '/demo/test/table/account_details/delete', // 批量删除
      },
      //表格组件
      cols: [], //表头
      tableData: [], //当前显示的一页的表格数据
      searchCondition: [], //搜索条件
      clearSelect: false, //是否清空选中项
      pageNumber: 1, //当前是第几页
      pageSize: 10, //每页显示的数据条数
      totalRecords: 200, //总共有多少条数据
      searchFilter: {}, // 搜索
      dialogTitle: '', // dialog标题
      attr: [],
      value: {},
      selectRows: [], // 选择的数据项
      dialogVisible: false,
      currentRow: {},
      //最后一列操作列显示的按钮
      operateButtons: ['编辑', '删除'],
      tableProps: [
        {name: 'cols', desc: '默认值：[]。表头数据。'},
        {name: 'tableData', desc: '默认值：[]。表格数据。'},
        {name: 'showSearch', desc: '默认值：false。是否显示搜索条件。'},
        {
          name: 'showSearchButton',
          desc: '默认值：true。是否显示搜索条件自带的按钮。如果没有其它的按钮，则置为true即可；如果有例如新增、删除等按钮，可能会造成查询按钮和其他按钮不在一行，此时可将其置为false,然后在slot中自己定义查询按钮'
        },
        {name: 'searchCondition', desc: '默认值：[]。搜索条件。'},
        {name: 'cellEditable', desc: '默认值：false。表格单元格是否可编辑。'},
        {name: 'stripe', desc: '默认值：true。表格单元格是否隔行变色。'},
        {name: 'border', desc: '默认值：true。是否带有纵向边框。'},
        {name: 'size', desc: '默认值：medium。Table 的尺寸    medium / small / mini。'},
        {name: 'fit', desc: '默认值：false。列的宽度是否自撑开。'},
        {name: 'highlight-current-row', desc: '默认值：false。是否要高亮当前行。'},
        {name: 'empty-text', desc: '默认值：暂无数据。空数据时显示的文本内容，也可以通过 slot="empty" 设置。'},
        {name: 'default-expand-all', desc: '默认值：false。是否默认展开所有行，当 Table 包含展开行存在或者为树形表格时有效。'},
        {name: 'expand-row-keys', desc: '默认值：[]。可以通过该属性设置 Table 目前的展开行，需要设置 row-key 属性才能使用，该属性为展开行的 keys 数组。'},
        {
          name: 'default-sort',
          desc: '默认值：{order:"ascending"}。默认的排序列的 prop 和顺序。它的prop属性指定默认的排序的列，order指定默认排序的顺序  ascending, descending   如果只指定了prop, 没有指定order, 则默认顺序是ascending。'
        },
        {name: 'tooltip-effect', desc: '默认值："light"。tooltip effect 属性  dark/light。'},
        {name: 'sum-text', desc: '默认值："合计"。合计行第一列的文本。'},
        {name: 'show-summary', desc: '默认值：false。是否在表尾显示合计行。'},
        {name: 'summary-method', desc: '默认值：null。自定义的合计计算方法。'},
        {name: 'span-method', desc: '默认值：null。合并行或列的计算方法。'},
        {
          name: 'select-on-indeterminate',
          desc: '默认值：true。在多选表格中，当仅有部分行被选中时，点击表头的多选框时的行为。若为 true，则选中所有行；若为 false，则取消选择所有行。'
        },
        {name: 'indent', desc: '默认值：16。展示树形数据时，树节点的缩进。'},
        {name: 'lazy', desc: '默认值：false。是否懒加载子节点数据。'},
        {name: 'load', desc: '默认值：null。加载子节点数据的函数，lazy 为 true 时生效，函数第二个参数包含了节点的层级信息。'},
        {name: 'tree-props', desc: '默认值：{ hasChildren: ""hasChildren", children: "children" }。渲染嵌套数据的配置选项。'},
        {name: 'canCheck', desc: '默认值：false。表格是否可多选。'},
        {name: 'disabledPartialCheck', desc: '默认值：false。是否开启checkbox部分禁用。'},
        {name: 'disabledPartialKey', desc: '默认值：""。开启checkbox部分禁用后，以什么值来判断是可用的。'},
        {name: 'disabledPartialLabel', desc: '默认值：""。开启checkbox部分禁用后，以什么key来判断是可用的。'},
        {name: 'showPaginator', desc: '默认值：false。表格是否分页。'},
        {name: 'pageNumber', desc: '默认值：1。如果表格分页，表示表格当前页数。'},
        {name: 'pageSize', desc: '默认值：10。如果表格分页，表示表格当前每页显示的数据的条数。'},
        {name: 'totalRecords', desc: '默认值：0。如果表格分页，显示总共有多少条数据。'},
        {name: 'layout', desc: '默认值：“prev, pager, next, jumper , sizes , total”。分页按钮显示配置及布局。'},
        {name: 'defaultSort', desc: '默认值：{}。表格默认排序项。'},
        {name: 'clearSelect', desc: '默认值：false。是否清空表格的选中项。'},
        {name: 'checkedRows', desc: '默认值：undefined。手动设置表格选中项。'},
        {name: 'showOperate', desc: '默认值：false。是否显示最后一列操作列。'},
        {name: 'buttonCount', desc: '默认值：0。显示几个按钮，来判断操作列显示的宽度100*buttonCount。'},
        {name: 'operateButtons', desc: '默认值：[]。操作列显示的按钮。'}
      ],
      tableMethods: [
        {name: 'selection-change', desc: '参数：selection。当前的所有选中项数据。当选择项发生变化时会触发该事件'},
        {name: 'select', desc: '参数：selection, row。当用户手动勾选数据行的 Checkbox 时触发的事件。'},
        {name: 'select-all', desc: '参数：selection。当用户手动勾选全选 Checkbox 时触发的事件。'},
        {name: 'cell-mouse-enter', desc: '参数：row, column, cell, event。当单元格 hover 进入时会触发该事件。'},
        {name: 'cell-mouse-leave', desc: '参数：row, column, cell, event。当单元格 hover 退出时会触发该事件。'},
        {name: 'cell-click', desc: '参数：row, column, cell, event。当某个单元格被点击时会触发该事件。'},
        {name: 'cell-dblclick', desc: '参数：row, column, cell, event。当某个单元格被双击击时会触发该事件。'},
        {name: 'row-click', desc: '参数：row, column,  event。当某行被单击时会触发该事件。'},
        {name: 'row-dblclick', desc: '参数：row, column,  event。当某行被双击时会触发该事件。'},
        {name: 'row-contextmenu', desc: '参数：row, column,  event。当某行被右键时会触发该事件。'},
         {name: 'header-click', desc: '参数：column,  event。当某一列的表头被点击时会触发该事件。'},
        {name: 'header-contextmenu', desc: '参数： column,  event。当某一列的表头被鼠标右键点击时触发该事件。'},
        {name: 'filter-change', desc: '参数：filters。当表格的筛选条件发生变化的时候会触发该事件，参数的值是一个对象，对象的 key 是 column 的 columnKey，对应的 value 为用户选择的筛选条件的数组。'},
        {name: 'current-change', desc: '参数：currentRow, oldCurrentRow。当表格的当前行发生变化的时候会触发该事件，如果要高亮当前行，请打开表格的 highlight-current-row 属性。'},
        {name: 'header-dragend', desc: '参数：newWidth, oldWidth, column, event。当拖动表头改变了列的宽度的时候会触发该事件。'},
        {name: 'expand-change', desc: '参数：row, (expandedRows | expanded)。当用户对某一行展开或者关闭的时候会触发该事件（展开行时，回调的第二个参数为 expandedRows；树形表格时第二参数为 expanded）。'},
        {name: 'sort-change', desc: '参数：{ column, prop, order }。当表格的排序条件发生变化的时候会触发该事件。'},
        {name: 'size-change', desc: '参数：pageSize。改变pageSize时触发。'},
        {name: 'current-page-change', desc: '参数：currentPage。改变pageNumber时触发。'},
        {name: 'pre-click', desc: '参数：currentPage。点击上一页时触发。'},
        {name: 'next-click', desc: '参数：currentPage。点击下一页时触发。'},
        {name: 'on-search', desc: '参数：更改后的查询条件数组。点击搜索条件的 查询 按钮时触发。'},
        {name: 'on-change-date', desc: '参数：查询条件中更改时间选择控件的值时触发。'},
        {name: 'on-change-year', desc: '参数：查询条件中更改年选择控件的值时触发。'},
        {name: 'on-change-option', desc: '参数：查询条件中单选下拉框更改选中项时触发。'},
        {name: 'on-change-multi-option', desc: '参数：查询条件中多选下拉框更改选中项时触发。'},
        {name: 'on-operate', desc: '参数：{btnText,index,row}。点击操作列的按钮时触发。'},
        {name: 'cell-change', desc: '参数：{cellType,index,col,row,cellParam}。单元格可编辑时，check或者switch等值发生变化时触发。'},
        {name: 'on-operate', desc: '参数：{btnText:btn,index: index,row: row}。点击操作列的按钮时触发。'},
      ],
    }
  },
  mounted() {
    this.getTableHeader();
  },
  computed: {
    showDel() {
      return this.dialogTitle === '删除' || this.dialogTitle === '批量删除';
    },
    showDelContent() {
      return this.dialogTitle === '批量删除' ? '确定要删除这些数据吗？' : '确定要删除该数据吗？';
    },
  },
  methods: {
    //获取表格的表头数据
    getTableHeader() {
      this.cols = [];
      this.searchCondition = [];
      // this.httpRequest("get", this.urls.getTableHeaderUrl, {}, {dataKey: 'value', hideSuccessTip: true}).then(res => {
      this.httpRequest("get", this.urls.getTableHeaderUrl, {}, {fullSuccess: true}).then(res => {
        this.cols = res.cols;
        res.cols.forEach((d) => {
          if (d.search) {
            let obj = this.cloneObj(d);
            if (-1 !== d.header.indexOf('时间') && (-1 === d.type.indexOf('range'))) {
              let start = this.cloneObj(d);
              start['metaField'] = start.field;
              start['label'] = start.header.replace('时间', '开始时间');
              start['field'] = start.field.replace('time', 'timeStart');
              start['metaField'] = start.field;
              start['value'] = null;
              this.searchCondition.push(start);
              let end = this.cloneObj(d);
              end['label'] = end.header.replace('时间', '结束时间');
              end['field'] = end.field.replace('time', 'timeEnd');
              start['metaField'] = start.field;
              end['value'] = null;
              this.searchCondition.push(end);
            } else {
              obj['label'] = d.header;
              obj['value'] = null;
              this.searchCondition.push(obj);
            }
          }
        });
        let filterResult = this.setFilter(this.searchCondition);
        if (!filterResult.tip) {
          this.searchFilter = filterResult.data;
          this.getTableData();
        } else {
          this.$message.warning(filterResult.tip)
        }
      }).catch(err => {
        console.log(err);
      });
    },
    //获取表格的表格数据
    getTableData() {
      let param = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        filter: this.searchFilter
      }
      //测试使用json文件数据
      this.httpRequest("get", this.urls.getTableDataUrl, param, {fullSuccess: true}).then(res => {
        this.tableData = res;
        this.totalRecords = res.length;

        /* this.httpRequest("post", this.urls.getTableDataUrl, param, {fullSuccess: true}).then(res => {
           this.tableData = res.value.data || [];
           this.totalRecords = res.value.rows;*/
      }).catch(err => {
        console.log(err);
      });
    },
    // 操作
    operate(str) {
      switch (str) {
        case "add":
          this.dialogTitle = "新增";
          this.attr = this.getFormItem(this.cols, 'addable')
          this.dialogVisible = true;
          this.value = this.getFormData(this.attr)
          this.$nextTick(() => {
            this.$refs.formRef.resetFields()
          })
          break;
        case "del":
          if (this.selectRows.length > 0) {
            this.dialogTitle = "批量删除";
            this.dialogVisible = true;
          } else {
            this.$message.warning('请先勾选要删除的数据')
          }
          break;
        default:
          break;
      }
    },
    // 操作
    clickOperate(e) {
      this.currentRow = e.row;
      switch (e.btnText) {
        case "编辑":
          this.dialogTitle = '编辑';
          this.attr = this.getFormItem(this.cols, 'editable')
          this.dialogVisible = true;
          this.$nextTick(() => {
            this.value = this.getEditFormData(this.attr, e.row)
            this.$refs.formRef.resetFields()
          })
          break;
        case "删除":
          this.dialogTitle = '删除';
          this.dialogVisible = true;
          break;
        default:
          break
      }
    },
    submit() {
      switch (this.dialogTitle) {
        case "新增":
          this.$refs.formRef.validate().then(res => {
            this.saveData('新增');
          })
          break;
        case "编辑":
          this.$refs.formRef.validate().then(res => {
            this.saveData('编辑');
          })
          break;
        case "删除":
          this.deleteData(this.currentRow['id'])
          break;
        case "批量删除":
          let arr = this.selectRows.map(el => {
            return el['id']
          });
          this.deleteInBatchesData(arr);
          break;
        default:
          break
      }
    },
    saveData(str) {
      this.httpRequest("post", this.urls.saveDataUrl, this.value, {hideEmptyTip: true}).then(res => {
        this.dialogVisible = false
        this.$message.success(`${str}成功！`)
        this.getTableData()
      })
    },
    updateData(str) {
      this.httpRequest("put", this.urls.saveDataUrl, this.value, {hideEmptyTip: true}).then(res => {
        this.dialogVisible = false
        this.$message.success(`${str}成功！`)
        this.getTableData()
      })
    },
    deleteData(id) {
      this.httpRequest("delete", `${this.urls.deleteDataUrl}/${id}`, {}, {hideEmptyTip: true}).then(res => {
        this.dialogVisible = false
        this.$message.success('删除成功！')
        this.getTableData()
        this.clearSelect = true;
        this.$nextTick(() => {
          this.clearSelect = false;
        })
      })
    },
    deleteInBatchesData(ids) {
      this.httpRequest("post", `${this.urls.deleteInBatches}`, ids, {hideEmptyTip: true}).then(res => {
        this.dialogVisible = false
        this.$message.success('删除成功！')
        this.getTableData()
        this.clearSelect = true;
        this.$nextTick(() => {
          this.clearSelect = false;
        })
      })
    },
    // 搜索
    searchData(e) {
      this.pageNumber = 1;
      let filterResult = this.setFilter(e);
      if (!filterResult.tip) {
        this.searchFilter = filterResult.data;
        this.getTableData();
      } else {
        this.$message.warning(filterResult.tip)
      }
    },
    // 勾选数据
    selectChange(arr) {
      this.selectRows = arr;
    },
    // 更改pageSize
    sizeChange(size) {
      this.pageNumber = 1;
      this.pageSize = size;
      this.getTableData();
    },
    // 更改page，上一页、下一页、改变currentPage
    pageChange(page) {
      this.pageNumber = page;
      this.getTableData();
    },
  },
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.table-demo-wrapper {
  width: 100%;
  height: 100%;
}

</style>
